package com.memo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.memo.db.DAO;
import com.memo.model.Congratulation;

public class AddGiftActivity extends Activity implements OnItemSelectedListener {
	private static Activity act;
	private static String phone;
	private static EditText etTime;
	private static EditText etDate;
	private static EditText etRecipient;
	private static Spinner spinCongrWay;	
	private static Uri imageUri;
	private static int photo_id = 1;
	private static final int PHONE_REQUEST_CODE = 1;
	private static final int CAPTURE_IMAGE_REQUEST_CODE = 2;
	private static final int GALLERY_IMAGE_REQUEST_CODE = 3;
	private static final String TAG = "AddGift";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_gift);
		act = this;
		String date = "";
		if (getIntent().hasExtra("date")) {
			Bundle extras = getIntent().getExtras();
			date = extras.getString("date");
		}
		initHeader(this, R.drawable.icon, R.string.add_gift);
		initBody(this, date);
	}

	private static void initHeader(Activity act, int icon, int text) {
		ImageView image = (ImageView) act.findViewById(R.id.header_icon);
		image.setImageResource(icon);

		TextView textView = (TextView) act.findViewById(R.id.header_title);
		textView.setText(act.getResources().getText(text));
	}

	private static void initBody(final Activity act, String date) {
		EditText etdate = (EditText) act.findViewById(R.id.add_gift_date);
		etdate.setText(date);
		etRecipient = (EditText) act.findViewById(R.id.add_gift_recipient);
		ImageView receiverPick = (ImageView) act.findViewById(R.id.add_gift_recipient_pick);
		receiverPick.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
				act.startActivityForResult(intent, PHONE_REQUEST_CODE);
			}
		});

		etDate = (EditText) act.findViewById(R.id.add_gift_date);
		ImageView datePick = (ImageView) act.findViewById(R.id.add_gift_date_pick);
		datePick.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String date = etDate.getText().toString();
				if (date.equals("")){
					final Calendar c = Calendar.getInstance();
					int mYear = c.get(Calendar.YEAR);
					int mMonth = c.get(Calendar.MONTH);
					int mDay = c.get(Calendar.DAY_OF_WEEK_IN_MONTH);
					new DatePickerDialog(v.getContext(), mDateSetListener, mYear,mMonth, mDay).show();
				}else{
					String[] dates = date.split("-");
					new DatePickerDialog(v.getContext(), mDateSetListener, Integer.parseInt(dates[0]), Integer.parseInt(dates[1])-1, Integer.parseInt(dates[2])).show();
				}

			}
		});
		
		etTime = (EditText) act.findViewById(R.id.add_gift_time);
		ImageView timePick = (ImageView) act.findViewById(R.id.add_gift_time_pick);
		timePick.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String time = etTime.getText().toString();
				if (time.equals("")){
					final Calendar c = Calendar.getInstance();
					int mHour = c.get(Calendar.HOUR_OF_DAY);
					int mMinute = c.get(Calendar.MINUTE);
					new TimePickerDialog(v.getContext(), mTimeSetListener, mHour,mMinute, false).show();
				}else{
					String[] times = time.split(" : ");
					new TimePickerDialog(v.getContext(), mTimeSetListener, Integer.parseInt(times[0]),Integer.parseInt(times[1]), false).show();
				}
			}
		});
		
//Gallery image click		
		ImageView galleryPick = (ImageView) act.findViewById(R.id.galery_add_gift);
		galleryPick.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {								
				Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				act.startActivityForResult(i, GALLERY_IMAGE_REQUEST_CODE); 
			}
		});
//Camera image click		
		ImageView cameraPick = (ImageView) act.findViewById(R.id.photo_add_gift);
		cameraPick.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {				
				String fileName = "new-photo"+photo_id+".jpg";
				ContentValues values = new ContentValues();
				values.put(MediaStore.Images.Media.TITLE, fileName);
				values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
				imageUri = act.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				act.startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE);

			}
		});
//Way to send greating		
		spinCongrWay = (Spinner) act.findViewById(R.id.congrWay);
		spinCongrWay.setOnItemSelectedListener((OnItemSelectedListener) act);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				act, R.array.congratulation_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinCongrWay.setAdapter(adapter);
		
//Add greating button		
		Button addGreating = (Button) act.findViewById(R.id.add_gift_btn);
		addGreating.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String name = etRecipient.getText().toString();
				String sDate = etDate.getText().toString();
				Date date = null;
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				   try {
					   date = sdf.parse(sDate);

				} catch (java.text.ParseException e) {
				    e.printStackTrace();
				}
				String time = etTime.getText().toString();
				String congrWay = spinCongrWay.getSelectedItem().toString();
				String sEmail = "";
				String sSubject = "";
				String sAttFiles = "";
				if (congrWay.equals("E-mail")){
					sEmail = ((EditText) act.findViewById(R.id.email)).getText().toString();
					sSubject = ((EditText) act.findViewById(R.id.message_subject)).getText().toString();
					sAttFiles = ((EditText) act.findViewById(R.id.attached_files_uris)).getText().toString();
				}
				String sBody = ((EditText) act.findViewById(R.id.message_body)).getText().toString();	
				Congratulation gift = new Congratulation(name, phone, date, time, congrWay, sEmail, sSubject, sBody, sAttFiles);
				DAO.insert(act, gift);	
				
				//creating an alarm
				Congratulation firstEvent = DAO.findFirstEven();
			}
		});
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		switch (pos) {
		case 0: { // SMS
			findViewById(R.id.message_subject).setVisibility(View.GONE);
			findViewById(R.id.email_row).setVisibility(View.GONE);
			findViewById(R.id.galery_add_gift).setVisibility(View.GONE);
			findViewById(R.id.photo_add_gift).setVisibility(View.GONE);
			findViewById(R.id.attached_files_uris).setVisibility(View.GONE);
			break;
		}
		case 1: { // E-mail
			findViewById(R.id.message_subject).setVisibility(View.VISIBLE);
			findViewById(R.id.email_row).setVisibility(View.VISIBLE);
			findViewById(R.id.galery_add_gift).setVisibility(View.VISIBLE);
			findViewById(R.id.photo_add_gift).setVisibility(View.VISIBLE);
			findViewById(R.id.attached_files_uris).setVisibility(View.VISIBLE);
			break;
		}

		case 2: { // MMS

			break;
		}
		}

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}
//----------------------------------------------------------------------------------------------------------------
	//Time and Date Picker listeners
	private static TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			etTime.setText(hourOfDay + " : " + minute);
		}
	};

	private static DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker arg0, int year, int month, int day) {
			month++;
			etDate.setText(year + "-" + month + "-" + day);
		}
	};
//---------------------------------------------------------------------------------------------------------------
	@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
        	switch (requestCode){
        		case PHONE_REQUEST_CODE:{
                        Uri uri = data.getData();
                        if (uri != null) {
                            Cursor c = null;
                            try {
                                c = act.getContentResolver().query(uri, null, null, null, null);
                                if (c != null && c.moveToFirst()) {
                                    phone = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
                                    String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                                    etRecipient.setText(name);
                                }
                            } catch(Exception e){
                                e.printStackTrace();
                            } finally {
                                if (c != null) {
                                    c.close();
                                }
                            }
                        }
        			break;
        		}
        		case CAPTURE_IMAGE_REQUEST_CODE: {
        			if (resultCode == RESULT_OK) {
        				findViewById(R.id.attached_files_icon).setVisibility(View.VISIBLE);
        				
        				TextView attached = (TextView)findViewById(R.id.attached_files_uris);
        				String tmp = attached.getText().toString();
        				tmp += imageUri.toString() + ";\n";
        				attached.setText(tmp);
        				    } else if (resultCode == RESULT_CANCELED) {
        				        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
        				    } else {
        				        Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
        				    }

        			break;
        		}
        		case GALLERY_IMAGE_REQUEST_CODE: {
        			findViewById(R.id.attached_files_icon).setVisibility(View.VISIBLE);
        			
        			imageUri = data.getData();
        			TextView attached = (TextView)findViewById(R.id.attached_files_uris);
        			String tmp = attached.getText().toString();
    				tmp += imageUri.toString() + ";";
    				attached.setText(tmp);
        			break;
        		}
        	}
            
        }
    }
//-------------------------------------------------------------------------------------------------------------------	
}
